
import os,cv2
import numpy as np

def resizeImg(img,rw,rh):
    return cv2.resize(img,(rw,rh))

def ratValue(img,save_img_size):
    _,w,h = img.shape[::-1]
    if(w>h):
        rat = save_img_size/(1.0*w)
        rw = save_img_size
        rh = int(h*rat)
    else:
        rat = save_img_size/(1.0*h)
        rh = save_img_size
        rw = int(h * rat)
    return rw,rh

def jpg2bgr(imgPath,dstPath,save_img_size):
    img = cv2.imread(imgPath)

    tmp = cv2.resize(img,(save_img_size,save_img_size))
    resized416 = tmp

    ### 等比例缩放
    # _,w,h = img.shape[::-1]
    # back = np.zeros_like(img)
    # back = cv2.resize(back,(save_img_size,save_img_size))
    # rw,rh = ratValue(img,save_img_size)
    # resized = resizeImg(img,rw,rh)
    # back[slice(0,rh),slice(0,rw)] = resized
    # resized416 = back

    (B, G, R) = cv2.split(resized416)

    name = imgPath.split("/")[-1].split(".")[0]
    saveimg =os.path.join(dstPath,name+str(save_img_size)+".bgr")
    print("name:",name)
    cv2.imwrite(os.path.join(dstPath,name+str(save_img_size)+".jpg"),resized416);


    with open(saveimg, 'wb')as fp:
        for i in range(save_img_size):
            for j in range(save_img_size):
                fp.write(B[i, j])
        for i in range(save_img_size):
            for j in range(save_img_size):
                fp.write(G[i, j])
        for i in range(save_img_size):
            for j in range(save_img_size):
                fp.write(R[i, j])
    cv2.imshow("img",resized416)
    cv2.waitKey(1)

def mkPath(path):
    if(os.path.exists(path)):
        return path
    os.mkdir(path)
    return path

def main():
    save_img_size = 608
    # imgsPath = "/mnt/data/3519/caffeCvtTools/nnie_bgr/boatSrc/images"
    imgsPath = "/media/jjn/文档/head/videos/003"
    dstPath = "../head_003_"+str(save_img_size)
    dstPath = mkPath(dstPath)
    # jpg2bgr("/mnt/data/3519/caffeCvtTools/nnie_bgr/boatSrc/black.png", dstPath, save_img_size)

    with open("file"+str(save_img_size)+".list", "w") as f:
        for imgPath in os.listdir(imgsPath):
            try:
                f.writelines(os.path.join(dstPath,imgPath.split(".")[0]+str(save_img_size)+".bgr")+"\n")
                jpg2bgr(os.path.join(imgsPath,imgPath),dstPath,save_img_size)
            except:
                continue

    # jpg2bgr("/mnt/data/3519/3559A/sample_src/mpp/sample/svp/multi-core4/data/nnie_image/rgb_planar/dog_bike_car.jpg")
    # jpg2bgr("./boat.png",save_img_size)

if __name__ == "__main__":
    main()